//
//  NetHandleBlock.m
//  HYHOME
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "NetHandleBlock.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"
@implementation NetHandleBlock
+ (void)networkingWithURL:(NSString *)string completeHandel:(void (^)(NSURLResponse *, NSData *, id))block{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            
            
            
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }if (isExistenceNetwork) {
        

    
    // 字符串转码
    NSString *codeStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:codeStr];
    
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 回到主线程(GCD).
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 如果有数据, 再执行
            if (data) {
                
               
                
                NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                
                
                NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetHandleBlock md5HexDigest:string],behind]];
                [data writeToFile:path  atomically:YES];

                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                // 调用 block
                block(response, data, result);
                });
            }
            
        });
        
    }];
    
    [dataTask resume];
    }else {
        NSLog(@"没有网络(断网)");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[file stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetHandleBlock md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        NSLog(@"%@",data);
        
        
        if (data == nil) {
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"alert" object:nil];            
        }else{
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            block(nil, nil, result);
        }
    }
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}



@end
